package org.example.config;

import brave.Tracing;
import brave.propagation.B3Propagation;
import brave.propagation.ExtraFieldPropagation;
import brave.propagation.ThreadLocalCurrentTraceContext;
import org.example.brave.http.HttpTracing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import zipkin2.Span;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.Sender;
import zipkin2.reporter.okhttp3.OkHttpSender;

@org.springframework.context.annotation.Configuration
public class Configuration {
    @Bean
    Sender sender() {
        return OkHttpSender.create("http://localhost:9411/api/v2/spans");
    }

    @Bean
    AsyncReporter<Span> reporter() {
        return AsyncReporter.create(sender());
    }

    @Bean
    Tracing tracing(@Value("${spring.application.name}") String name) {
        return Tracing.newBuilder().localServiceName(name)
                .propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
                .currentTraceContext(ThreadLocalCurrentTraceContext.create())
                .spanReporter(reporter()).build();
    }

    @Bean
    HttpTracing httpTracing(Tracing tracing) {
        return HttpTracing.create(tracing);
    }
}
